package com.css.zfzx.data.primary.base.repository.impl;

import com.css.zfzx.data.primary.base.repository.SuperRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Iterator;

/**
 * @Description: data
 * @Author: lhl
 * @CreateDate: 2021/10/12 9:34
 */
@Repository
public class SuperRepositoryImpl<T> implements SuperRepository<T> {
    @PersistenceContext
    private EntityManager em;
    @Value("${spring.jpa.properties.hibernate.jdbc.batch_size}")
    private int BATCH_SIZE;

    @Override
    public <S extends T> Iterable<S> batchSave(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            em.persist(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0) {
                em.flush();
                em.clear();
            }
        }
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        return var1;
    }
    @Override
    public <S extends T> Iterable<S> batchUpdate(Iterable<S> var1) {
        Iterator<S> iterator = var1.iterator();
        int index = 0;
        while (iterator.hasNext()) {
            em.merge(iterator.next());
            index++;
            if (index % BATCH_SIZE == 0) {
                em.flush();
                em.clear();
            }
        }
        if (index%10000==0){
            System.out.println(index);
        }
        if (index % BATCH_SIZE != 0) {
            em.flush();
            em.clear();
        }
        System.out.println(index);
        return var1;
    }
}
